#!/usr/bin/env node

import { spawn } from 'child_process';
import { LocalRepository } from './dist/local-repository.js';
import { ClassFinder } from './dist/class-finder.js';
import fs from 'fs/promises';
import path from 'path';

async function testCFRDirectly() {
  console.log('🔧 直接测试CFR反编译器...');
  
  const classFinder = new ClassFinder();
  const localRepository = new LocalRepository(classFinder);
  
  // Set repository path
  localRepository.setLocalRepositoryPath('/mnt/d/mavenrepository');
  
  try {
    // Find AuditDomain class
    const allArtifacts = await localRepository.scanLocalRepository();
    const targetArtifact = allArtifacts.find(artifact => 
      artifact.artifactId.includes('hzero-boot-customize')
    );
    
    if (!targetArtifact) {
      console.log('❌ 未找到目标artifact');
      return;
    }
    
    console.log(`📦 使用artifact: ${targetArtifact.artifactId}`);
    
    const classes = await localRepository.getLocalArtifactClasses(targetArtifact);
    const auditDomainClass = classes.find(cls => cls.fullName.includes('AuditDomain'));
    
    if (!auditDomainClass) {
      console.log('❌ 未找到AuditDomain类');
      return;
    }
    
    console.log(`🎯 找到类: ${auditDomainClass.fullName}`);
    
    // Extract class bytecode
    const classBytes = await classFinder.getClassSource(auditDomainClass);
    if (!classBytes) {
      console.log('❌ 无法提取类字节码');
      return;
    }
    
    console.log(`✅ 提取了 ${classBytes.length} 字节的类文件`);
    
    // Create temp directory and class file
    const tempDir = `/tmp/decompile-test-${Date.now()}`;
    await fs.mkdir(tempDir, { recursive: true });
    
    const className = auditDomainClass.fullName.split('.').pop();
    const packagePath = auditDomainClass.packageName.replace(/\./g, '/');
    const classFileDir = path.join(tempDir, packagePath);
    await fs.mkdir(classFileDir, { recursive: true });
    
    const classFilePath = path.join(classFileDir, `${className}.class`);
    await fs.writeFile(classFilePath, classBytes);
    
    console.log(`📁 类文件保存到: ${classFilePath}`);
    
    // Test CFR directly
    console.log('🔧 使用CFR反编译...');
    
    const cfrPath = './tools/cfr.jar';
    const outputDir = path.join(tempDir, 'output');
    await fs.mkdir(outputDir, { recursive: true });
    
    return new Promise((resolve) => {
      const args = [
        '-jar', cfrPath,
        '--outputdir', outputDir,
        '--silent', 'false',
        classFilePath
      ];
      
      console.log(`执行命令: java ${args.join(' ')}`);
      
      const process = spawn('java', args);
      
      let stdout = '';
      let stderr = '';
      
      process.stdout.on('data', (data) => {
        stdout += data.toString();
      });
      
      process.stderr.on('data', (data) => {
        stderr += data.toString();
      });
      
      process.on('close', async (code) => {
        console.log(`CFR进程退出，代码: ${code}`);
        
        if (stdout) {
          console.log('CFR输出:');
          console.log(stdout);
        }
        
        if (stderr) {
          console.log('CFR错误:');
          console.log(stderr);
        }
        
        try {
          // Look for generated Java file
          const expectedJavaFile = path.join(outputDir, packagePath, `${className}.java`);
          console.log(`查找生成的Java文件: ${expectedJavaFile}`);
          
          try {
            const javaSource = await fs.readFile(expectedJavaFile, 'utf-8');
            console.log('\n🎉 CFR反编译成功！');
            console.log('='.repeat(80));
            console.log('📄 AuditDomain.java 源代码:');
            console.log('='.repeat(80));
            console.log(javaSource);
            console.log('='.repeat(80));
            
            // Save to current directory
            const outputFile = `./AuditDomain_CFR.java`;
            await fs.writeFile(outputFile, javaSource);
            console.log(`💾 源代码已保存到: ${outputFile}`);
            
          } catch (readError) {
            console.log(`❌ 无法读取生成的Java文件: ${readError.message}`);
            
            // List files in output directory
            console.log('输出目录内容:');
            try {
              const files = await fs.readdir(outputDir, { recursive: true });
              console.log(files);
            } catch (listError) {
              console.log(`无法列出文件: ${listError.message}`);
            }
          }
          
        } catch (error) {
          console.error(`处理CFR输出时出错: ${error.message}`);
        }
        
        // Cleanup
        try {
          await fs.rm(tempDir, { recursive: true, force: true });
        } catch (cleanupError) {
          console.log(`清理临时文件失败: ${cleanupError.message}`);
        }
        
        resolve();
      });
      
      process.on('error', (error) => {
        console.error(`CFR进程启动失败: ${error.message}`);
        resolve();
      });
    });
    
  } catch (error) {
    console.error('测试失败:', error);
  }
}

testCFRDirectly();